MarkMenuItemDispatcher.getMenuItem   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
c 0
b 0
f 0
dl 0
loc 12
rs 10
1
import { toggleMark } from 'prosemirror-commands';
2
import AbstractMenuItemDispatcher from './AbstractMenuItemDispatcher';
3
import MenuItem from '../MenuItem';
4
import { svgIcon } from '../MDI';
5
6
export default class MarkMenuItemDispatcher extends AbstractMenuItemDispatcher {
7
    constructor(markType, iconName, title) {
8
        super();
9
10
        this.markType = markType;
11
        this.iconName = iconName;
12
        this.title = title;
13
    }
14
15
    isAvailable(schema) {
16
        return !!schema.marks[this.markType];
17
    }
18
19
    /**
20
     * Determine if the mark is currently active at the cursor
21
     *
22
     * taken from prosemirror-example-setup
23
     *
24
     * @param {EditorState} state the editor's current state
25
     * @param {MarkType} type type of the mark based on the schema (e.g. schema.marks.strong )
26
     * @return {boolean} True if the mark is currently active
27
     */
28
    static markActive(state, type) {
29
        const {
30
            from, $from, to, empty,
31
        } = state.selection;
32
        if (empty) {
33
            return type.isInSet(state.storedMarks || $from.marks());
34
        }
35
        return state.doc.rangeHasMark(from, to, type);
36
    }
37
38
    getMenuItem(schema) {
39
        if (!this.isAvailable(schema)) {
40
            throw new Error(`Mark ${this.markType} is not available in Schema!`);
41
        }
42
43
        return new MenuItem({
44
            command: toggleMark(schema.marks[this.markType]),
45
            icon: svgIcon(this.iconName),
46
            label: this.title,
47
            isActive: editorState => MarkMenuItemDispatcher.markActive(editorState, schema.marks[this.markType]),
48
        });
49
    }
50
}
51